﻿using System;
using System.Globalization;
using System.Web;
using System.Web.Compilation;
using System.Web.Mvc;
using System.Web.UI;


namespace Wayloop.Blog.Presentation.Extensions
{
    public static class ResourceExtensions
    {
        public static string Resource(this HtmlHelper htmlhelper, string expression, params object[] args)
        {
            string virtualPath = GetVirtualPath(htmlhelper);

            return GetResourceString(htmlhelper.ViewContext.HttpContext, expression, virtualPath, args);
        }


        private static string GetResourceString(HttpContextBase httpContext, string expression, string virtualPath, object[] args)
        {
            var expressionContext = new ExpressionBuilderContext(virtualPath);
            var expressionBuilder = new ResourceExpressionBuilder();
            var expressionFields = (ResourceExpressionFields) expressionBuilder.ParseExpression(expression, typeof (string), expressionContext);
            object resourceObject = GetResourceObject(httpContext, virtualPath, expressionFields);

            return String.Format(Convert.ToString(resourceObject), args);
        }


        private static object GetResourceObject(HttpContextBase httpContext, string virtualPath, ResourceExpressionFields expressionFields)
        {
            if (String.IsNullOrEmpty(expressionFields.ClassKey)) {
                return httpContext.GetLocalResourceObject(virtualPath, expressionFields.ResourceKey, CultureInfo.CurrentUICulture);
            }

            return httpContext.GetGlobalResourceObject(expressionFields.ClassKey, expressionFields.ResourceKey, CultureInfo.CurrentUICulture);
        }


        private static string GetVirtualPath(HtmlHelper htmlHelper)
        {
            var view = htmlHelper.ViewDataContainer as TemplateControl;
            if (view != null) {
                return view.AppRelativeVirtualPath;
            }

            return null;
        }
    }
}